<template>
  <view class="staff-add-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <u-form :model="formData" :rules="rules" ref="formRef" label-width="120rpx">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="user" color="#667eea" size="16"></u-icon>
            <text>基本信息</text>
          </view>
          
          <u-form-item label="真实姓名" prop="realName" required>
            <u-input 
              v-model="formData.realName"
              placeholder="请输入真实姓名"
              maxlength="50"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="工号" prop="employeeNo" required>
            <u-input 
              v-model="formData.employeeNo"
              placeholder="请输入工号"
              maxlength="20"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="手机号" prop="phone" required>
            <u-input 
              v-model="formData.phone"
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="邮箱" prop="email">
            <u-input 
              v-model="formData.email"
              placeholder="请输入邮箱"
              type="email"
              class="form-input"
            />
          </u-form-item>
        </view>
        
        <!-- 工作信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="briefcase" color="#667eea" size="16"></u-icon>
            <text>工作信息</text>
          </view>
          
          <u-form-item label="所属公司" prop="selectedPropertyCompanyId" required>
            <view class="picker-input-wrapper" @click="handleCompanyPickerClick">
              <view class="picker-display">
                <text class="picker-text">{{ selectedPropertyCompanyName || '请选择所属公司' }}</text>
                <u-icon name="arrow-down" size="16" color="#999"></u-icon>
              </view>
            </view>
          </u-form-item>
          
          <u-form-item label="角色" prop="roleId" required>
            <view class="picker-input-wrapper" @click="handleRolePickerClick">
              <view class="picker-display">
                <text class="picker-text">{{ selectedRoleName || '请选择角色' }}</text>
                <u-icon name="arrow-down" size="16" color="#999"></u-icon>
              </view>
            </view>
          </u-form-item>
          
          <u-form-item label="入职日期" prop="entryDate" required>
            <u-input 
              v-model="formData.entryDate"
              placeholder="请选择入职日期"
              readonly
              @click="showDatePicker = true"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="员工状态" prop="status" required>
            <u-radio-group v-model="formData.status" direction="row">
              <u-radio 
                v-for="item in statusOptions" 
                :key="item.value" 
                :name="item.value"
                :label="item.label"
              >
                {{ item.label }}
              </u-radio>
            </u-radio-group>
          </u-form-item>
        </view>
        
      </u-form>
    </view>
    
    <!-- 底部操作按钮 -->
    <view class="action-section">
      <u-button 
        type="default" 
        text="取消"
        size="large"
        @click="handleCancel"
        class="action-button"
      />
      <u-button 
        type="primary" 
        text="保存"
        size="large"
        @click="handleSubmit"
        :loading="submitting"
        class="action-button"
      />
    </view>
    
    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showDatePicker"
      v-model="selectedDate"
      mode="date"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="handleDateConfirm"
      @cancel="showDatePicker = false"
    />
    
    <!-- 物业公司选择器 -->
    <u-picker
      :show="showPropertyCompanyPicker"
      :columns="propertyCompanyColumns"
      @confirm="handlePropertyCompanyConfirm"
      @cancel="showPropertyCompanyPicker = false"
    />
    
    <!-- 角色选择器 -->
    <u-picker
      :show="showRolePicker"
      :columns="roleColumns"
      @confirm="handleRoleConfirm"
      @cancel="showRolePicker = false"
    />
  </view>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { staffApi } from '@/api/staff'
import { userInfoApi } from '@/api/user'
import { useAuthStore } from '@/store/auth'

export default {
  name: 'StaffAdd',
  setup() {
    // 响应式数据
    const formRef = ref(null)
    const submitting = ref(false)
    const showDatePicker = ref(false)
    const selectedDate = ref(new Date().getTime())
    
    // 物业公司选择相关
    const showPropertyCompanyPicker = ref(false)
    const propertyCompanyList = ref([])
    const selectedPropertyCompanyId = ref(null)
    const selectedPropertyCompanyName = ref('')
    const propertyCompanyColumns = ref([[]])
    
    // 角色选择相关
    const showRolePicker = ref(false)
    const roleList = ref([])
    const selectedRoleId = ref(null)
    const selectedRoleName = ref('')
    const roleColumns = ref([[]])
    
    // 日期范围
    const minDate = new Date(2020, 0, 1).getTime()
    const maxDate = new Date().getTime()
    
    // 表单数据
    const formData = reactive({
      realName: '',
      employeeNo: '',
      phone: '',
      email: '',
      roleId: null, // 选中的角色ID
      entryDate: '',
      status: 1,
      selectedPropertyCompanyId: null // 选中的物业公司ID
    })
    
    // 状态选项
    const statusOptions = ref([
      { label: '在职', value: 1 },
      { label: '待入职', value: 2 }
    ])
    
    // 角色选项 - 根据业务需求固定数据
    const roleOptions = ref([
      { id: 2, name: '区域管理员', code: 'REGION_ADMIN' },
      { id: 3, name: '社区管理员', code: 'COMMUNITY_ADMIN' },
      { id: 4, name: '物业人员', code: 'PROPERTY_STAFF' },
      { id: 5, name: '安保人员', code: 'SECURITY_STAFF' },
      { id: 6, name: '维修人员', code: 'REPAIR_STAFF' },
      { id: 9, name: '物业管理员', code: 'PROPERTY_ADMIN' },
      { id: 10, name: '楼栋管理员', code: 'BUILDING_ADMIN' },
      { id: 11, name: '单元管理员', code: 'UNIT_ADMIN' },
      { id: 12, name: '房户管理员', code: 'HOUSEHOLD_ADMIN' },
      { id: 16, name: '安保管理', code: 'SECURITY_ADMIN' },
      { id: 17, name: '保洁人员', code: 'CLEANING_STAFF' },
      { id: 18, name: '保洁管理', code: 'CLEANING_ADMIN' },
      { id: 19, name: '停车人员', code: 'PARKING_STAFF' },
      { id: 20, name: '停车管理', code: 'PARKING_ADMIN' }
    ])
    
    // 表单验证规则
    const rules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '姓名长度在2-50个字符之间', trigger: 'blur' }
      ],
      employeeNo: [
        { required: true, message: '请输入工号', trigger: 'blur' },
        { min: 2, max: 20, message: '工号长度在2-20个字符之间', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      roleId: [
        { required: true, message: '请选择角色', trigger: 'blur' }
      ],
      entryDate: [
        { required: true, message: '请选择入职日期', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择员工状态', trigger: 'blur' }
      ],
      selectedPropertyCompanyId: [
        { required: true, message: '请选择所属公司', trigger: 'blur' }
      ]
    }
    
    // 日期确认
    const handleDateConfirm = (value) => {
      const date = new Date(value)
      formData.entryDate = date.toLocaleDateString('zh-CN')
      showDatePicker.value = false
    }
    
    
    // 表单提交
    const handleSubmit = async () => {
      try {
        console.log('开始表单提交，当前表单数据:', formData)
        
        // 手动验证必填字段
        if (!formData.realName || formData.realName.trim() === '') {
          uni.showToast({
            title: '请输入真实姓名',
            icon: 'error'
          })
          return
        }
        
        if (!formData.employeeNo || formData.employeeNo.trim() === '') {
          uni.showToast({
            title: '请输入工号',
            icon: 'error'
          })
          return
        }
        
        if (!formData.phone || formData.phone.trim() === '') {
          uni.showToast({
            title: '请输入手机号',
            icon: 'error'
          })
          return
        }
        
        // 验证手机号格式
        const phonePattern = /^1[3-9]\d{9}$/
        if (!phonePattern.test(formData.phone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'error'
          })
          return
        }
        
        // 验证邮箱格式（如果填写了）
        if (formData.email && formData.email.trim() !== '') {
          const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailPattern.test(formData.email)) {
            uni.showToast({
              title: '请输入正确的邮箱格式',
              icon: 'error'
            })
            return
          }
        }
        
        if (!formData.selectedPropertyCompanyId) {
          uni.showToast({
            title: '请选择所属公司',
            icon: 'error'
          })
          return
        }
        
        if (!formData.roleId) {
          uni.showToast({
            title: '请选择角色',
            icon: 'error'
          })
          return
        }
        
        if (!formData.status) {
          uni.showToast({
            title: '请选择员工状态',
            icon: 'error'
          })
          return
        }
        
        if (!formData.entryDate || formData.entryDate.trim() === '') {
          uni.showToast({
            title: '请选择入职日期',
            icon: 'error'
          })
          return
        }
        
        submitting.value = true
        
        // 根据选择的角色获取对应的userType和position
        const selectedRole = roleOptions.value.find(role => role.id === formData.roleId)
        const userType = selectedRole ? selectedRole.code : 'PROPERTY_COMPANY_USER'
        const position = selectedRole ? selectedRole.name : '物业公司用户'
        
        console.log('选择的角色:', selectedRole)
        console.log('对应的userType:', userType)
        console.log('对应的position:', position)
        
        // 准备提交数据 - 严格按照后端DTO字段映射
        const submitData = {
          propertyCompanyId: formData.selectedPropertyCompanyId,
          username: formData.phone, // 使用手机号作为用户名
          realName: formData.realName,
          phone: formData.phone,
          email: formData.email || '',
          userType: userType, // 根据选择的角色动态设置用户类型
          position: position, // 根据选择的角色动态设置职位名称
          department: '', // 部门字段，暂时为空
          employeeNo: formData.employeeNo,
          joinDate: formData.entryDate ? new Date(formData.entryDate).toISOString().split('T')[0] : null,
          remark: `员工状态：${formData.status === 1 ? '在职' : '待入职'}`,
          roleId: formData.roleId // 添加角色ID字段
        }
        
        console.log('提交员工数据:', submitData)
        
        // 调用后端API保存员工信息 - 使用物业公司用户新增接口
        const response = await staffApi.addPropertyCompanyUser(submitData)
        
        if (response && response.code === 200) {
          uni.showToast({
            title: '员工添加成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(response?.message || '添加失败')
        }
        
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'error'
        })
      } finally {
        submitting.value = false
      }
    }
    
    // 获取用户关联的物业公司列表
    const loadPropertyCompanyList = async () => {
      try {
        const authStore = useAuthStore()
        const userInfo = authStore.userInfo

        if (!userInfo?.id) {
          console.error('用户信息不存在，无法获取物业公司列表')
          uni.showToast({
            title: '用户信息不存在',
            icon: 'error'
          })
          return
        }

        // 调用后端API获取用户关联的物业公司列表
        const response = await userInfoApi.getUserPropertyCompanies(userInfo.id)
        
        if (response && response.code === 200 && response.data) {
          // 转换数据格式，提取物业公司信息
          propertyCompanyList.value = response.data.map(item => ({
            id: item.propertyCompanyId,
            companyName: item.propertyCompanyName,
            companyCode: item.propertyCompanyCode || item.propertyCompanyName,
            position: item.position,
            department: item.department,
            employeeNo: item.employeeNo,
            status: item.status
          }))

          // 构建选择器数据
          propertyCompanyColumns.value = [[
            ...propertyCompanyList.value.map(company => ({
              text: company.companyName,
              value: company.id
            }))
          ]]

          // 默认选中第一个物业公司
          if (propertyCompanyList.value.length > 0) {
            const firstCompany = propertyCompanyList.value[0]
            selectedPropertyCompanyId.value = firstCompany.id
            selectedPropertyCompanyName.value = firstCompany.companyName
            formData.selectedPropertyCompanyId = firstCompany.id
          }

          console.log('物业公司列表加载成功:', propertyCompanyList.value)
          console.log('物业公司列表详情:', propertyCompanyList.value.map(company => ({
            id: company.id,
            name: company.companyName,
            type: typeof company.id
          })))
        } else {
          console.warn('获取物业公司列表失败:', response)
          uni.showToast({
            title: '获取物业公司列表失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('加载物业公司列表失败:', error)
        uni.showToast({
          title: '加载物业公司列表失败',
          icon: 'error'
        })
      }
    }


    // 处理物业公司选择器点击
    const handleCompanyPickerClick = () => {
      console.log('点击物业公司选择器')
      showPropertyCompanyPicker.value = true
    }

    // 处理角色选择器点击
    const handleRolePickerClick = () => {
      console.log('点击角色选择器')
      showRolePicker.value = true
    }

    // 物业公司选择确认
    const handlePropertyCompanyConfirm = (event) => {
      try {
        // 严格按照App端编码规范处理u-picker的confirm事件参数
        console.log('物业公司选择事件参数:', event)
        
        // 参数校验 - 确保事件对象和必要属性存在
        if (!event || !event.value || !Array.isArray(event.value) || event.value.length === 0) {
          console.error('物业公司选择事件参数无效:', event)
          uni.showToast({
            title: '选择失败，请重试',
            icon: 'error'
          })
          showPropertyCompanyPicker.value = false
          return
        }
        
        // 获取选中的物业公司ID - 处理不同的数据格式
        let selectedCompanyId = event.value[0]
        console.log('选中的物业公司ID原始数据:', selectedCompanyId)
        
        // 如果选中的是对象格式 {text: '公司名', value: 1015}，提取value
        if (selectedCompanyId && typeof selectedCompanyId === 'object' && selectedCompanyId.value) {
          selectedCompanyId = selectedCompanyId.value
          console.log('提取的物业公司ID:', selectedCompanyId)
        }
        
        // 查找对应的物业公司信息
        const selectedCompany = propertyCompanyList.value.find(company => company.id === selectedCompanyId)
        
        if (selectedCompany) {
          // 更新选中的物业公司信息
          selectedPropertyCompanyId.value = selectedCompany.id
          selectedPropertyCompanyName.value = selectedCompany.companyName
          formData.selectedPropertyCompanyId = selectedCompany.id
          
          console.log('成功选择物业公司:', selectedCompany)
          
          // 显示成功提示
          uni.showToast({
            title: `已选择：${selectedCompany.companyName}`,
            icon: 'success',
            duration: 1500
          })
        } else {
          console.error('未找到对应的物业公司信息，ID:', selectedCompanyId)
          uni.showToast({
            title: '选择失败，未找到对应公司',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('物业公司选择处理异常:', error)
        uni.showToast({
          title: '选择处理异常，请重试',
          icon: 'error'
        })
      } finally {
        // 确保选择器关闭
        showPropertyCompanyPicker.value = false
      }
    }

    // 角色选择确认
    const handleRoleConfirm = (event) => {
      try {
        // 严格按照App端编码规范处理u-picker的confirm事件参数
        console.log('角色选择事件参数:', event)
        
        // 参数校验 - 确保事件对象和必要属性存在
        if (!event || !event.value || !Array.isArray(event.value) || event.value.length === 0) {
          console.error('角色选择事件参数无效:', event)
          uni.showToast({
            title: '选择失败，请重试',
            icon: 'error'
          })
          showRolePicker.value = false
          return
        }
        
        // 获取选中的角色ID - 处理不同的数据格式
        let roleId = event.value[0]
        console.log('选中的角色ID原始数据:', roleId)
        
        // 如果选中的是对象格式 {text: '角色名', value: 2}，提取value
        if (roleId && typeof roleId === 'object' && roleId.value) {
          roleId = roleId.value
          console.log('提取的角色ID:', roleId)
        }
        
        // 查找对应的角色信息
        const selectedRole = roleOptions.value.find(role => role.id === roleId)
        
        if (selectedRole) {
          // 更新选中的角色信息
          selectedRoleId.value = selectedRole.id
          selectedRoleName.value = selectedRole.name
          formData.roleId = selectedRole.id
          
          console.log('成功选择角色:', selectedRole)
          
          // 显示成功提示
          uni.showToast({
            title: `已选择：${selectedRole.name}`,
            icon: 'success',
            duration: 1500
          })
        } else {
          console.error('未找到对应的角色信息，ID:', roleId)
          uni.showToast({
            title: '选择失败，未找到对应角色',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('角色选择处理异常:', error)
        uni.showToast({
          title: '选择处理异常，请重试',
          icon: 'error'
        })
      } finally {
        // 确保选择器关闭
        showRolePicker.value = false
      }
    }

    // 取消操作
    const handleCancel = () => {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消添加员工吗？未保存的数据将丢失。',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    }
    
    // 初始化角色数据
    const initRoleData = async () => {
      try {
        // 构建选择器数据
        roleColumns.value = [[
          ...roleOptions.value.map(role => ({
            text: role.name,
            value: role.id
          }))
        ]]
        
        // 默认选中第一个角色
        if (roleOptions.value.length > 0) {
          const firstRole = roleOptions.value[0]
          selectedRoleId.value = firstRole.id
          selectedRoleName.value = firstRole.name
          formData.roleId = firstRole.id
          
          console.log('默认选中第一个角色:', firstRole)
        }
        
        console.log('角色数据初始化成功:', roleOptions.value)
      } catch (error) {
        console.error('角色数据初始化失败:', error)
      }
    }

    // 页面加载
    onMounted(async () => {
      console.log('页面开始初始化...')
      
      // 设置默认入职日期为今天
      const today = new Date()
      formData.entryDate = today.toLocaleDateString('zh-CN')
      
      // 设置默认员工状态
      formData.status = 1
      console.log('设置默认状态:', formData.status)
      
      // 初始化角色数据
      await initRoleData()
      console.log('角色初始化完成，roleId:', formData.roleId)
      
      // 加载物业公司列表
      await loadPropertyCompanyList()
      console.log('物业公司加载完成，selectedPropertyCompanyId:', formData.selectedPropertyCompanyId)
      
      console.log('页面初始化完成，最终表单数据:', formData)
    })
    
    return {
      formRef,
      submitting,
      showDatePicker,
      selectedDate,
      minDate,
      maxDate,
      formData,
      statusOptions,
      rules,
      // 物业公司选择相关
      showPropertyCompanyPicker,
      propertyCompanyList,
      selectedPropertyCompanyId,
      selectedPropertyCompanyName,
      propertyCompanyColumns,
      // 角色选择相关
      showRolePicker,
      roleList,
      selectedRoleId,
      selectedRoleName,
      roleColumns,
      handleDateConfirm,
      handleCompanyPickerClick,
      handlePropertyCompanyConfirm,
      handleRolePickerClick,
      handleRoleConfirm,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style lang="scss" scoped>
.staff-add-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-content {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 40rpx;
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.form-input {
  background: #f8f9fa;
  border-radius: 8rpx;
}

/* 选择器输入框样式 */
.picker-input-wrapper {
  width: 100%;
  cursor: pointer;
  
  .picker-display {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f8f9fa;
    border-radius: 8rpx;
    padding: 24rpx 20rpx;
    min-height: 88rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;
    
    &:active {
      background: #f0f0f0;
      border-color: #667eea;
    }
    
    .picker-text {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      line-height: 1.4;
      
      &:empty::before {
        content: attr(placeholder);
        color: #999;
      }
    }
  }
}

.action-section {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #f0f0f0;
  
  .action-button {
    flex: 1;
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .form-content {
    margin: 15rpx;
    padding: 20rpx;
  }
  
  .form-section {
    margin-bottom: 30rpx;
  }
}
</style>
